package com.wyp.controller.access.interceptor;

import com.alibaba.fastjson.JSON;
import com.wyp.common.CodeMsg;
import com.wyp.common.Result;
import com.wyp.controller.access.AccessLimit;
import com.wyp.controller.access.UserContext;
import com.wyp.entity.User;
import com.wyp.service.UserService;
import com.wyp.service.impl.UserServiceImpl;
import com.wyp.utils.redis.RedisService;
import com.wyp.utils.redis.prekey.pre.MSKey;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 限流的拦截器
 *
 * @author: Oliver
 */
@Service
public class AccessInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    RedisService redisService;
    @Autowired
    UserService userService;


    /**
     * 发生在controller请求执行之前 返回为false请求不会到达方法中
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            User user = getUser(request, response);
            //将获取到的user存放到ThreadLocal中，等待填充参数使用
            UserContext.setUser(user);
            HandlerMethod hm = (HandlerMethod) handler;
            //获取方法上的注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null) {
                return true;
            }
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();
            int seconds = accessLimit.seconds();
            String key = request.getRequestURI();
            if (needLogin) {
                if (user == null) {
                    //如果用户user==null 返回错误信息
                    render(response, CodeMsg.SESSION_ERROR);
                    return false;
                }
                key += "_" + user.getId();
            }

            MSKey accessKey = MSKey.withExpire(seconds);
            Integer urlNum = redisService.get(accessKey, key, Integer.class);
            if (urlNum == null) {
                redisService.set(accessKey, key, 1);
            } else if (urlNum < maxCount) {
                redisService.incr(accessKey, key);
            } else {
                //返回错误信息
                render(response, CodeMsg.ACCESS_LIMIT_REACHED);
            }

        }
        return super.preHandle(request, response, handler);
    }

    private void render(HttpServletResponse response, CodeMsg codeMsg) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str = JSON.toJSONString(Result.error(codeMsg));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }

    /**
     * 根据token获取用户信息
     *
     * @param request
     * @param response
     * @return
     */
    private User getUser(HttpServletRequest request, HttpServletResponse response) {
        String paramToken = request.getParameter(UserServiceImpl.COOKI_NAME_TOKEN);
        String cookieToken = getCookieValue(request, UserServiceImpl.COOKI_NAME_TOKEN);
        if (StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)) {
            return null;
        }
        String token = StringUtils.isEmpty(paramToken) ? cookieToken : paramToken;
        return userService.getUserByToken(token, response);
    }

    /**
     * 获取cookie中的token信息
     *
     * @param request
     * @param cookieName
     * @return
     */
    private String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length <= 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                return cookie.getValue();
            }
        }
        return null;
    }
}
